#include "../app.h"
#include "tuya_cloud_types.h"
#include "tal_api.h"
#include "tkl_output.h"
#include "tkl_gpio.h"

static void parent_del_cb(lv_event_t *e)
{
    tkl_gpio_deinit(TUYA_GPIO_NUM_1);
    lv_timer_t *timer = (lv_timer_t *)lv_event_get_user_data(e);
    lv_timer_del(timer);
}

static void read_test_func(lv_timer_t *timer)
{
    LV_UNUSED(timer);
    lv_obj_t *btn2 = (lv_obj_t *)timer->user_data;
    TUYA_GPIO_LEVEL_E read_level;
    tkl_gpio_read(TUYA_GPIO_NUM_12, &read_level);
    if (read_level == 0)
    {
        PR_DEBUG("GPIO read low level");
        lv_obj_add_state(btn2, LV_STATE_CHECKED);
    }
    else
    {
        PR_DEBUG("GPIO read high level");
        lv_obj_clear_state(btn2, LV_STATE_CHECKED);
    }
}

int app_hw_gpio_2(lv_obj_t *parent)
{

    lv_obj_t *btn2 = lv_btn_create(parent);
    lv_obj_align(btn2, LV_ALIGN_CENTER, 0, 0);
    lv_obj_add_flag(btn2, LV_OBJ_FLAG_CHECKABLE);
    lv_obj_clear_flag(btn2, LV_OBJ_FLAG_CLICKABLE);
    lv_obj_set_height(btn2, LV_SIZE_CONTENT);

    lv_obj_t *label = lv_label_create(btn2);
    lv_label_set_text(label, "status");
    lv_obj_center(label);

    TUYA_GPIO_BASE_CFG_T in_pin_cfg = {
        .mode = TUYA_GPIO_PULLUP,
        .direct = TUYA_GPIO_INPUT,
    };
    tkl_gpio_init(TUYA_GPIO_NUM_12, &in_pin_cfg);

    lv_timer_t *timer = lv_timer_create(read_test_func, 200, (void *)btn2);
    lv_obj_add_event_cb(parent, parent_del_cb, LV_EVENT_DELETE, (void *)timer);

    return 0;
}
